<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item :label="$t('page.system.user.username')">
          <el-input
            v-model="searchForm.username"
            :placeholder="$t('page.system.user.username')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.user.realName')">
          <el-input
            v-model="searchForm.realName"
            :placeholder="$t('page.system.user.realName')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.user.phone')">
          <el-input
            v-model="searchForm.phone"
            :placeholder="$t('page.system.user.phone')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.user.status')">
          <el-select
            v-model="searchForm.status"
            :placeholder="$t('page.system.user.status')"
            clearable
            style="width: 120px"
          >
            <el-option :label="$t('page.system.user.normal')" :value="1" />
            <el-option :label="$t('page.system.user.disabled')" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            {{ $t('page.system.user.search') }}
          </el-button>
          <el-button @click="handleReset">
            {{ $t('page.system.user.reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        + {{ $t('page.system.user.add') }}
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        {{ $t('page.system.user.batchDelete') }}
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      />
      <el-table-column
        prop="username"
        :label="$t('page.system.user.username')"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="realName"
        :label="$t('page.system.user.realName')"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="phone"
        :label="$t('page.system.user.phone')"
        min-width="130"
      />
      <el-table-column
        prop="role.name"
        :label="$t('page.system.user.role')"
        min-width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-tag :type="row.role?.roleKey === 'ADMIN' ? 'danger' : 'primary'">
            {{ row.role?.name || '-' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        :label="$t('page.system.user.status')"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? $t('page.system.user.normal') : $t('page.system.user.disabled') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="loginCount"
        :label="$t('page.system.user.loginCount')"
        width="100"
        align="center"
      />
      <el-table-column
        prop="lastLoginAt"
        :label="$t('page.system.user.lastLoginAt')"
        width="160"
        align="center"
      >
        <template #default="{ row }">
          {{ row.lastLoginAt || '-' }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('page.system.user.operation')"
        width="250"
        align="center"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="primary"
            text
            @click="handleDetail(row)"
          >
            {{ $t('page.system.user.detail') }}
          </el-button>
          <el-button
            size="small"
            type="primary"
            text
            @click="handleEdit(row)"
          >
            {{ $t('page.system.user.edit') }}
          </el-button>
          <el-button
            size="small"
            :type="row.status === 1 ? 'warning' : 'success'"
            text
            @click="handleStatusChange(row, row.status === 1 ? 0 : 1)"
          >
            {{ row.status === 1 ? $t('page.system.user.disable') : $t('page.system.user.enable') }}
          </el-button>
          <el-button
            size="small"
            type="danger"
            text
            @click="handleDelete(row)"
          >
            {{ $t('page.system.user.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.pageNo"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户表单弹窗 -->
    <UserForm
      v-model:visible="formVisible"
      :form-data="currentUser"
      :is-edit="isEdit"
      @submit="handleFormSubmit"
    />

    <!-- 用户详情弹窗 -->
    <UserDetailModal
      v-model:visible="detailVisible"
      :user-data="currentUser"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';

import type { UserDetail, UserFormData, UserListParams } from '#/api/system/user';
import { deleteUsersApi, getUserDetailApi, getUserListApi, updateUserApi } from '#/api/system/user';
import { $t } from '#/locales';

import UserDetailModal from './components/UserDetail.vue';
import UserForm from './components/UserForm.vue';

// 搜索表单
const searchForm = reactive<UserListParams>({
  username: '',
  realName: '',
  phone: '',
  status: undefined,
});

// 表格数据
const tableData = ref<UserDetail[]>([]);
const loading = ref(false);
const selectedRows = ref<UserDetail[]>([]);

// 分页
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

// 表单弹窗
const formVisible = ref(false);
const currentUser = ref<Partial<UserDetail>>({});
const isEdit = ref(false);

// 详情弹窗
const detailVisible = ref(false);

// 获取用户列表
const getUserList = async () => {
  loading.value = true;
  try {
    // 过滤掉空值参数，只传入有值的查询条件
    const params: any = {
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
    };
    
    // 只有当搜索条件有值时才添加到参数中
    if (searchForm.username && searchForm.username.trim()) {
      params.username = searchForm.username.trim();
    }
    if (searchForm.realName && searchForm.realName.trim()) {
      params.realName = searchForm.realName.trim();
    }
    if (searchForm.phone && searchForm.phone.trim()) {
      params.phone = searchForm.phone.trim();
    }
    if (searchForm.status !== undefined && searchForm.status !== null) {
      params.status = searchForm.status;
    }

    try {
      const response = await getUserListApi(params);

      console.log("API响应数据：", response);
      console.log("response类型：", typeof response);

      // 检查API响应格式 - 实际API直接返回数据，不包装在 {code, data} 中
      if (response && (response as any).result && Array.isArray((response as any).result)) {
        // 直接使用API返回的数据结构
        console.log("使用API数据");
        tableData.value = (response as any).result || [];
        pagination.total = (response as any).total || 0;
        console.log("表格数据：", tableData.value);
        console.log("总数：", pagination.total);
      } else if (response && (response as any).data && (response as any).data.code === 200) {
        // 兼容包装格式的API
        console.log("使用包装格式API数据");
        const responseData = (response as any).data.data;
        tableData.value = responseData?.result || [];
        pagination.total = responseData?.total || 0;
      } else {
        console.error('API响应格式异常:', response);
        tableData.value = [];
        pagination.total = 0;
        ElMessage.error('API响应格式异常，请检查接口');
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      ElMessage.error('获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.pageNo = 1;
  getUserList();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    realName: '',
    phone: '',
    status: undefined,
  });
  pagination.pageNo = 1;
  getUserList();
};

// 新增
const handleAdd = () => {
  currentUser.value = {};
  isEdit.value = false;
  formVisible.value = true;
};

// 编辑
const handleEdit = (row: UserDetail) => {
  currentUser.value = { ...row };
  isEdit.value = true;
  formVisible.value = true;
};

// 查看详情
const handleDetail = async (row: UserDetail) => {
  try {
    const response = await getUserDetailApi(row.id);
    console.log('用户详情API响应:', response);
    
    // 检查API响应格式
    if (response && (response as any).username) {
      // 直接返回用户详情数据
      console.log('使用API返回的用户详情数据');
      currentUser.value = response as unknown as UserDetail;
      detailVisible.value = true;
    } else if (response && (response as any).data && (response as any).data.code === 200) {
      // 包装格式的API响应
      console.log('使用包装格式的用户详情数据');
      currentUser.value = (response as any).data.data;
      detailVisible.value = true;
    } else {
      console.error('用户详情API响应格式异常:', response);
      ElMessage.error('获取用户详情失败');
    }
  } catch (error) {
    console.error('获取用户详情失败:', error);
    ElMessage.error('获取用户详情失败');
  }
};

// 状态变更
const handleStatusChange = async (row: UserDetail, newStatus: number) => {
  try {
    const response = await updateUserApi({
      id: row.id,
      status: newStatus
    } as UserFormData); // 使用类型断言解决类型不匹配问题
    console.log('状态修改API响应:', response);
    
    if (response && ((response as any).success || (response as any).id)) {
      // API调用成功
      console.log('状态修改成功，刷新列表');
      ElMessage.success(newStatus === 1 ? '用户已启用' : '用户已禁用');
      getUserList();
    } else {
      console.error('状态修改API响应异常:', response);
      ElMessage.error('状态修改失败');
    }
  } catch (error) {
    console.error('状态修改失败:', error);
    ElMessage.error('状态修改失败');
  }
};

// 删除
const handleDelete = async (row: UserDetail) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.username}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const response = await deleteUsersApi([row.id]);
    console.log('删除用户API响应:', response);
    
    if (response && ((response as any).success || (response as any).data?.code === 200)) {
      ElMessage.success('删除用户成功');
      getUserList();
    } else {
      ElMessage.error('删除用户失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error);
      ElMessage.error('删除用户失败');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的用户');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个用户吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const userIds = selectedRows.value.map(row => row.id);
    const response = await deleteUsersApi(userIds);
    
    if (response && ((response as any).success || (response as any).data?.code === 200)) {
      ElMessage.success('批量删除用户成功');
      selectedRows.value = [];
      getUserList();
    } else {
      ElMessage.error('批量删除用户失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }
};

// 选择变更
const handleSelectionChange = (selection: UserDetail[]) => {
  selectedRows.value = selection;
};

// 分页大小变更
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageNo = 1;
  getUserList();
};

// 页码变更
const handleCurrentChange = (page: number) => {
  pagination.pageNo = page;
  getUserList();
};

// 表单提交
const handleFormSubmit = () => {
  formVisible.value = false;
  getUserList();
};

// 页面加载
onMounted(() => {
  getUserList();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}

.toolbar .el-button {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 
 